import { defineStore } from 'pinia'
import { ref, computed } from 'vue' // 添加 computed 导入

export const useUserStore = defineStore('user', () => {
    // 从 localStorage 获取用户信息
    const currentUser = ref(JSON.parse(localStorage.getItem('currentUser')) || null)

    // 计算属性：判断是否登录
    const isLoggedIn = computed(() => !!currentUser.value)

    // 设置用户信息
    const setUser = (user) => {
        currentUser.value = user
        // 保存到 localStorage
        localStorage.setItem('currentUser', JSON.stringify(user))
    }

    // 清除用户信息
    const clearUserState = () => {
        currentUser.value = null
        // 清除 localStorage
        localStorage.removeItem('currentUser')
    }

    return {
        currentUser,
        isLoggedIn,
        setUser,
        clearUserState
    }
}, {
    persist: true // 启用状态持久化
})